package com.woniuxy.realm;

import com.woniuxy.service.UserService;
import com.woniuxy.service.UserServiceImpl;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Set;


public class MyRealm extends AuthorizingRealm {
    private Logger logger=Logger.getLogger(AuthorizingRealm.class);
    private UserService userService;
    //实例化UserService
    public MyRealm() {
        userService=new UserServiceImpl();
    }
    @Override
    public String getName() {
        return "myRealm";
    }
    //授权的时候调用
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("=====doGetAuthorizationInfo授权的时候被调用======");
        //获取用户名
        String userName=(String) principalCollection.getPrimaryPrincipal();
        //调用业务层方法通过用户名查找角色的集合
        Set<String> roleNames=userService.getRolesByUserName(userName);
        //调用业务层方法通过用户名查找该用户所拥有权限的集合
        Set<String> permissionNames=userService.getPermissionsByUserName(userName);
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //设置角色名称集合到authorizationInfo对象
        authorizationInfo.setRoles(roleNames);
        //设置权限名称的集合到authorizationInfo
        authorizationInfo.setStringPermissions(permissionNames);
        return authorizationInfo;
    }
    //认证的时候调用
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        logger.info("=====doGetAuthenticationInfo认证的时候被调用======");
        //获取用户名
        String userName=(String) authenticationToken.getPrincipal();
        //调用业务层的通过用户名可以查找到的方法
        String pwd=userService.getPwdByUserName(userName);
        /**
         * SimpleAuthenticationInfo三个参数含义
         * Object principal：用户名
         * Object credentials:密码
         * String realmName:realm的名称
         */
        AuthenticationInfo authenticationInfo=new SimpleAuthenticationInfo(userName,pwd,this.getName());
        return authenticationInfo;
    }
}
